#include"node.h"
SListNode* BuySListNode(SLTDateType x)
{
	SListNode* newnode=(SListNode*)malloc(sizeof(SListNode));
	if (newnode == NULL)
	{
		perror("buy fail");
		exit(10086);
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}

void SListPrint(SListNode* plist)
{
	SListNode* pcur = plist;
	while (pcur!=NULL)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL");
}

void SListPushBack(SListNode** pplist, SLTDateType x)
{
	SListNode*newnode = BuySListNode(x);
	if (*pplist == NULL)
	{
		*pplist = newnode;
	}
	else
	{
		SListNode* ptail = *pplist;
		while (ptail->next)
		{
			ptail = ptail->next;
		}
		ptail->next = newnode;
	}
}

void SListPushFront(SListNode** pplist, SLTDateType x)
{
	assert(pplist);
	SListNode* newnode = BuySListNode(x);
	newnode->next = *pplist;
	*pplist = newnode;
}

void SListPopBack(SListNode** pplist)
{
	assert(pplist&&*pplist);
	if ((*pplist) -> next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		SListNode* pcr = *pplist;
		SListNode* pev = NULL;
		while (pcr->next)
		{
			pev = pcr;
			pcr = pcr->next;
		}
		pev->next=NULL;
		free(pcr);
		pcr = NULL;

	}
}

void SListPopFront(SListNode** pplist)
{
	assert(*pplist&& pplist);
	if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		SListNode* pev = *pplist;
		*pplist = pev->next;
		free(pev);
		pev = NULL;
	}
}

SListNode* SListFind(SListNode* plist, SLTDateType x)
{
	SListNode* pcr = plist;
	while (pcr->next)
	{
		if (pcr->data==x)
		{
			printf("%d\n", x);
			return pcr;
		}
		pcr = pcr->next;
	}
	printf("Can't find\n");
	return NULL;
}

void SListInsertAfter (SListNode* pos, SLTDateType x)
{
	SListNode* newnode = BuySListNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

void SLTInsert(SListNode** pphead, SListNode* pos, SLTDateType x)
{
	assert(pphead && pos);
	if (pos == *pphead)
	{
		SListPushFront(pphead, x);
	}
	else
	{
		SListNode* newnode = BuySListNode(x);
		SListNode* pre = *pphead;
		while (pre->next != pos)
		{
			pre = pre->next;
		}
		newnode->next = pos;
		pre->next = newnode;
	}
}

void SListEraseAfter(SListNode* pos)
{
	assert(pos&&pos->next);
	SListNode* now = pos->next;
	pos->next = pos->next->next;
	free(now);
	now = NULL;
}

void SLTErase(SListNode** pphead, SListNode* pos)
{
	assert(pphead&&pos);
	if (pos == *pphead)
	{
		SListPopFront(pphead);
	}
	else
	{
		SListNode* prc = *pphead;
		while (prc->next != pos)
		{
			prc = prc->next;
		}
		prc->next = pos->next;
		free(pos);
		pos = NULL;
	}
}

void SLTDestroy(SListNode** pphead)
{
	assert(pphead);
	SListNode* pev = *pphead;
	while (pev)
	{
		SListNode* next = pev->next;
		free(pev);
		pev = next;
	}
	*pphead = NULL;
}